
<?php

require_once LIBRARIES_ENTITIES . DS . 'Database.php';
require_once LIBRARIES_ENTITIES . DS . 'Categories.php';
require_once LIBRARIES_ENTITIES . DS . 'Videos.php';
require_once LIBRARIES_TOOLS . DS . 'Utility.php';
require_once LIBRARIES_TOOLS . DS . 'XTemplate.php';
require_once LIBRARIES_TOOLS . DS . 'PagerBackEnd.php';

class VideoController {

    public function invoke() {

        // function list
        $groupFunctions = $_SESSION['groupFunctions'];

        // check view permission
        if (Utility::checkPermission('view', $groupFunctions, VIDEO_MANAGEMENT)) {

            // directory path
            $dir = dirname(__FILE__);

            $view = '';
            if (isset($_GET['view'])) {
                $view = $_GET['view'];
            }

            $action = '';
            if (isset($_POST['hdAction'])) {
                $action = $_POST['hdAction'];
            }



            $task = '';
            if (isset($_GET['task'])) {
                $task = $_GET['task'];
            }


            $rowToView = 10;
            if (isset($_POST["limit"])) {
                $rowToView = $_POST["limit"];
            }


            switch ($action) {
                case 'orderdown':
                    $ID = $_POST["hdID"];
                    $result = $this->orderVideo($ID, 'down');

                    Utility::redirectCurrentPage();
                    break;
                case 'orderup':
                    $ID = $_POST["hdID"];
                    $result = $this->orderVideo($ID, 'up');
                    Utility::redirectCurrentPage();
                    break;
                case 'remove':
                    $values = $_POST["cid"];
                    $result = $this->deleteVideo($values);
                    if ($result == OK) {
                        Utility::messageBox('Xóa thành công');
                        Utility::redirectCurrentPage();
                    }
                    break;
                case 'add':
                case 'addAndExit':

                    // title
                    $title = $_POST['txtTitle'];

                    // file path
                    $filePath = $_POST['hdVideo'];

                    // form youtube
                    $fromYoutube = 0;
                    if ($_POST['rdoFilePath'] == 'youtube') {
                        $fromYoutube = 1;
                    }

                    // image
                    $image = $_POST['hdImage'];

                    // date
                    $date = Utility::formatDateTime($_POST['txtCreatedDate']);

                    // status
                    $status = $_POST['rdoStatus'];

                    // width
                    $width = $_POST['txtWidth'];

                    // height
                    $height = $_POST['txtHeight'];

                    // createdUserID
                    $createdUserID = $_SESSION["session"]["sUserID"];

                    $result = $this->addVideo($title, $filePath, $image, $date, $status, $fromYoutube, $width, $height, $createdUserID);

                    if ($result == OK) {

                        if ($action == 'add') {
                            Utility::messageBox('Thêm thành công');
                            Utility::redirectCurrentPage();
                        } else {
                            Utility::redirect(".?com=com_video&task=view");
                        }
                    }
                    break;
                case 'edit':
                case 'editAndExit':

                    // ID
                    $ID = $_POST['hdID'];

                    // title
                    $title = $_POST['txtTitle'];

                    // file path
                    $filePath = $_POST['hdVideo'];

                    // form youtube
                    $fromYoutube = 0;
                    if ($_POST['rdoFilePath'] == 'youtube') {
                        $fromYoutube = 1;
                    }

                    // image
                    $image = $_POST['hdImage'];

                    // date
                    $date = Utility::formatDateTime($_POST['txtModifiedDate']);

                    // status
                    $status = $_POST['rdoStatus'];

                    // width
                    $width = $_POST['txtWidth'];

                    // height
                    $height = $_POST['txtHeight'];

                    // createdUserID
                    $createdUserID = $_SESSION["session"]["sUserID"];

                    $result = $this->updateVideo($ID, $title, $filePath, $image, $date, $status, $fromYoutube, $width, $height, $createdUserID);

                    if ($result == OK) {
                        if ($action == 'edit') {
                            Utility::messageBox('Sửa thành công');
                            Utility::redirectCurrentPage();
                        } else {
                            Utility::redirect(".?com=com_video&task=view");
                        }
                    }
                    break;
            }








            if ($task == 'view') {
                $viewFile = $dir . '/views/video_list.html';
                $xtemplate = new XTemplate($viewFile);

                // CHECK PERMISSION
                // check add button
                if (Utility::checkPermission('add', $groupFunctions, VIDEO_MANAGEMENT)) {
                    $xtemplate->parse('main.add_button');
                }
                // check delete button
                if (Utility::checkPermission('delete', $groupFunctions, VIDEO_MANAGEMENT)) {
                    $xtemplate->parse('main.delete_button');
                }


                $indexCheckBox = 1;

                $rurrentPage = 1;
                if (isset($_POST["page"])) {
                    $rurrentPage = $_POST["page"];
                }


                // chỉ mục (số thứ tự của bài viết) bài viết
                $index = 1;

                $videos = $this->getVideoList();

                $pager = PagerBackEnd::getPagerData(count($videos), $rowToView, $rurrentPage);


                if ($videos != null) {

                    $indexCheckBox = 1;



                    foreach ($videos as $video) {

                        if ($index > $pager->offset && $index <= $pager->limit) {

                            $xtemplate->assign('INDEX', $index);

                            $xtemplate->assign('INDEX_CHECKBOX', $indexCheckBox);

                            $xtemplate->assign('ID', $video->getID());
                            $xtemplate->assign('IMAGE', $video->getImage());
                            $xtemplate->assign('TITLE', $video->getTitle());
                            $xtemplate->assign('WIDTH', $video->getWidth());
                            $xtemplate->assign('HEIGHT', $video->getHeight());

                            $xtemplate->assign('CREATED_USER', $video->getCreatedUser()->getFullname());
                            $xtemplate->assign('MODIFIED_USER', $video->getModifiedUser()->getFullname());

                            $xtemplate->assign('CREATED_DATE', Utility::formatDateTimeToView($video->getCreatedDate()));
                            $xtemplate->assign('MODIFIED_DATE', Utility::formatDateTimeToView($video->getModifiedDate()));

                            $filePath = $video->getFilePath();

                            if ($video->getFromYouTube() == 1) {
                                $filePath = substr($filePath, strpos($filePath, '?v=') + 3, strlen($filePath));
                                $xtemplate->assign('FILEPATH', $filePath);
                                $xtemplate->parse('main.video_list.on_youtube');
                            } else {
                                $xtemplate->assign('FILEPATH', $filePath);
                                $xtemplate->parse('main.video_list.on_server');
                            }

                            // check update permission                            
                            if (Utility::checkPermission('update', $groupFunctions, VIDEO_MANAGEMENT)) {
                                $xtemplate->parse('main.video_list.update_button');
                            } else {
                                $xtemplate->parse('main.video_list.update_button_disable');
                            }


                            // status
                            if ($video->getStatus() == 1) {
                                $xtemplate->assign('STATUS_ACTION', 'unpublish');
                                $xtemplate->assign('STATUS_IMAGE', 'publish_g.png');
                            } else {
                                $xtemplate->assign('STATUS_ACTION', 'publish');
                                $xtemplate->assign('STATUS_IMAGE', 'publish_r.png');
                            }

                            // order
                            if ($index == 1) {
                                $xtemplate->parse('main.video_list.down_arrow');
                            } else if ($index == count($videos)) {
                                $xtemplate->parse('main.video_list.up_arrow');
                            } else {
                                $xtemplate->parse('main.video_list.up_down_arrow');
                            }

                            $xtemplate->parse('main.video_list');

                            $indexCheckBox++;
                        }
                        $index++;
                    }
                }

                $xtemplate->assign('LIMIT_LIST', Utility::getLimitList($rowToView));
                $xtemplate->assign('ROW_TO_VIEW', $rowToView);
                $xtemplate->assign('CURRENT_PAGE', $rurrentPage);
                $xtemplate->assign('AMOUNT_OF_PAGE', $pager->numPages);
                $xtemplate->assign('PAGING_HTML', $pager->paging);
                $xtemplate->parse('main');
                $xtemplate->out('main');
            } else if ($task == 'add') {

                // check add permission
                if (Utility::checkPermission('add', $groupFunctions, VIDEO_MANAGEMENT)) {
                    $xtemplate = new XTemplate($dir . '/views/video_add.html');
                    $xtemplate->assign('TODAY', date('d/m/Y'));
                    $xtemplate->assign('UPLOAD_FOLDER', UPLOAD_FOLDER);
                    $xtemplate->parse('main');
                    $xtemplate->out('main');
                } else {
                    echo ERROR_PERMISSION;
                }
            } else if ($task == 'edit') {

                // check add permission
                if (Utility::checkPermission('update', $groupFunctions, VIDEO_MANAGEMENT)) {
                    $ID = '';
                    if (isset($_GET['ID'])) {
                        $ID = $_GET['ID'];
                    }

                    $video = $this->getVideoByID($ID);

                    if ($video != null) {

                        $viewFile = $dir . '/views/video_edit.html';

                        $xtemplate = new XTemplate($viewFile);

                        $xtemplate->assign('ID', $video->getID());
                        $xtemplate->assign('CREATED_DATE', Utility::formatDateTimeToView($video->getCreatedDate()));
                        $xtemplate->assign('MODIFIED_DATE', Utility::formatDateTimeToView($video->getModifiedDate()));

                        $xtemplate->assign('TITLE', $video->getTitle());
                        $xtemplate->assign('IMAGE', $video->getImage());

                        $xtemplate->assign('FILE_PATH', $video->getFilePath());
                        $xtemplate->assign('WIDTH', $video->getWidth());
                        $xtemplate->assign('HEIGHT', $video->getHeight());



                        if ($video->getStatus() == 1) {
                            $xtemplate->parse('main.status_true');
                        } else {
                            $xtemplate->parse('main.status_false');
                        }

                        if ($video->getFromYouTube() == 1) {
                            $xtemplate->parse('main.on_youtube');
                            $xtemplate->parse('main.hide_browse_button');
                        } else {
                            $xtemplate->parse('main.on_server');
                        }

                        $xtemplate->parse('main');
                        $xtemplate->out('main');
                    } else {
                        Utility::redirect('.?com=com_video&task=view');
                    }
                } else {
                    echo ERROR_PERMISSION;
                }
            }
        } else {
            echo ERROR_PERMISSION;
        }
    }

    // get list of video
    private function getVideoList() {
        $db = new Database();
        try {
            $video = new Videos();
            return $video->getList($db);
        } catch (PDOException $exc) {
            $db->rollback();
            echo $exc->getMessage();
            exit();
        }
    }

    // add a video
    private function addVideo($title, $videoPath, $image, $date, $status, $fromYoutube, $width, $height, $createdUserID) {
        $db = new Database();
        try {
            $video = new Videos();

            $video->setTitle($title);

            $video->setFilePath($videoPath);

            $video->setImage($image);
            $video->setCreatedDate($date);
            $video->setModifiedDate($date);
            $video->setFromYouTube($fromYoutube);
            $video->setCreatedUserID($createdUserID);
            $video->setModifiedUserID($createdUserID);
            $video->setWidth($width);
            $video->setHeight($height);
            $video->setStatus($status);
            $video->setOrder($video->getMaxOrder($db));
            $result = $video->add($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            $db->rollback();
            echo $exc->getMessage();
            exit();
        }
    }

    // delete many video
    private function deleteVideo($values) {
        $db = new Database();
        try {
            for ($i = 0; $i < count($values); $i++) {
                $video = new Videos();
                $video->setID($values[$i]);
                $video->delete($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }
    

    // add a video
    private function updateVideo($ID, $title, $videoPath, $image, $date, $status, $fromYoutube, $width, $height, $createdUserID) {
        $db = new Database();
        try {
            $video = new Videos();
            $video->setID($ID);
            $video->setTitle($title);
            $video->setFilePath($videoPath);
            $video->setImage($image);
            $video->setModifiedDate($date);
            $video->setFromYouTube($fromYoutube);
            $video->setModifiedUserID($createdUserID);
            $video->setWidth($width);
            $video->setHeight($height);
            $video->setStatus($status);
            $result = $video->update($db);

            $db->submitChanges();

            return $result;
        } catch (PDOException $exc) {
            $db->rollback();
            echo $exc->getMessage();
            exit();
        }
    }

    private function getVideoByID($ID) {
        $db = new Database();
        try {
            $video = new Videos();
            $video->setID($ID);
            $video->getByID($db);
            $db->submitChanges();
            return $video;
        } catch (PDOException $exc) {
            $db->rollback();
            echo $exc->getMessage();
            exit();
        }
    }

    private function orderVideo($ID, $action) {
        $db = new Database();
        try {
            $video = new Videos();
            $video->setID($ID);
            if ($action == 'up') {
                $video->orderUp($db);
            } else {
                $video->orderDown($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

}
